<template>
  <view class="machine-bind-page">
    <!-- 头部 -->
    <view class="header">
      <text class="title">我的机具</text>
      <text class="subtitle">查看您的机具</text>
    </view>


    <!-- 已绑定的机具列表 -->
    <view class="machine-list">
      <view class="list-header">
        <text class="list-title">已绑定的机具</text>
      </view>
      
      
      <view v-if="machines.length === 0" class="empty">
        <text>暂无绑定的机具</text>
      </view>
      
      <view v-else class="machine-items">
        <view 
          v-for="machine in machines" 
          :key="machine.id" 
          class="machine-item"
          :class="{ 'expanded': expandedMachine && expandedMachine.id === machine.id }"
        >
          <view class="machine-info">
            <view class="info-row">
              <text class="label">机身号：</text>
              <text class="value">{{ machine.possn }}</text>
            </view>
            <view class="info-row">
              <text class="label">商户号：</text>
              <text class="value">{{ machine.merch_no }}</text>
            </view>
            <view class="info-row">
              <text class="label">商户名称：</text>
              <text class="value">{{ machine.merch_name }}</text>
            </view>
            <view class="info-row">
              <text class="label">绑定时间：</text>
              <text class="value">{{ machine.bind_time }}</text>
            </view>
            <view class="info-row">
              <text class="label">状态：</text>
              <text class="value status" :class="{ 'active': machine.bind_status == 1 }">
                {{ machine.bind_status == 1 ? '已激活' : '未激活' }}
              </text>
            </view>
          </view>
          
          <view class="machine-actions">
            <view class="machine-status">
              <text class="status-text">
                已绑定
              </text>
            </view>
          </view>
          
          <view class="machine-footer">
            <text class="view-logs-btn" @click="toggleTradeLogs(machine)">
              查看流水
            </text>
          </view>
          
          <!-- 交易流水抽屉 -->
          <view 
            v-if="expandedMachine && expandedMachine.id === machine.id" 
            class="trade-drawer"
          >
            <view class="drawer-header">
              <view class="drawer-title-section">
                <text class="drawer-title">交易流水</text>
                <text class="drawer-subtitle">{{ machine.possn }} - {{ machine.merch_name }}</text>
              </view>
            </view>
            
            <view v-if="tradeLogsLoading && tradeLogs.length === 0" class="loading-logs">
              <text>加载中...</text>
            </view>
            
            <view v-else-if="tradeLogs.length === 0" class="empty-logs">
              <text>暂无交易记录</text>
            </view>
            
            <view v-else class="trade-logs">
              <view 
                v-for="log in tradeLogs" 
                :key="log.id" 
                class="trade-log-item"
              >
                <view class="log-header">
                  <text class="log-amount">￥{{ parseFloat(log.amount).toFixed(2) }}</text>
                  <text class="log-status" :class="{ 'success': log.status_text === '成功', 'failed': log.status_text === '失败' }">
                    {{ log.status_text }}
                  </text>
                </view>
                <view class="log-details">
                  <view class="detail-row">
                    <text class="label">交易时间：</text>
                    <text class="value">{{ formatTradeTime(log.trans_time || log.create_time) }}</text>
                  </view>
                  <view class="detail-row">
                    <text class="label">交易ID：</text>
                    <text class="value">{{ log.trans_id }}</text>
                  </view>
                  <view class="detail-row">
                    <text class="label">商户号：</text>
                    <text class="value">{{ log.merch_no }}</text>
                  </view>
                  <view class="detail-row">
                    <text class="label">卡号：</text>
                    <text class="value">{{ log.card_no }}</text>
                  </view>
                  <view class="detail-row">
                    <text class="label">手续费：</text>
                    <text class="value">￥{{ parseFloat(log.fee_amount).toFixed(2) }}</text>
                  </view>
                  <view v-if="log.ret_msg" class="detail-row">
                    <text class="label">备注：</text>
                    <text class="value">{{ log.ret_msg }}</text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 加载更多 -->
            <view v-if="hasMoreLogs" class="load-more-logs">
              <text class="load-more-btn" @click="loadMoreLogs">加载更多</text>
            </view>
          </view>
        </view>
      </view>
    </view>

  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { post } from '@/utils/http'
import { ApitestUrl } from '@/utils/api'
import { onPullDownRefresh } from '@dcloudio/uni-app'

// 响应式数据
const machines = ref([])
const loading = ref(false)

// 交易流水相关
const expandedMachine = ref(null)
const tradeLogs = ref([])
const tradeLogsLoading = ref(false)
const hasMoreLogs = ref(false)
const currentPage = ref(1)
const pageSize = 10

// 获取用户绑定的机具列表
const getMachines = async () => {
  loading.value = true
  
  try {
    const response = await post(ApitestUrl + '/api/LishuaCallback/getUserMachines', {})

    if (response.code === 1) {
      machines.value = response.data || []
    } else {
      uni.showToast({
        title: response.msg || '获取失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取机具列表失败:', error)
    uni.showToast({
      title: '获取失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}



// 下拉刷新处理
onPullDownRefresh(async () => {
  console.log('触发下拉刷新')
  await getMachines()
  // 停止下拉刷新动画
  uni.stopPullDownRefresh()
})

// 格式化交易时间
const formatTradeTime = (timeStr) => {
  if (!timeStr) return ''
  
  // 如果是时间戳格式
  if (typeof timeStr === 'number') {
    return new Date(timeStr * 1000).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
  
  // 如果是字符串格式 20241123120710
  if (typeof timeStr === 'string' && timeStr.length === 14) {
    const year = timeStr.substring(0, 4)
    const month = timeStr.substring(4, 6)
    const day = timeStr.substring(6, 8)
    const hour = timeStr.substring(8, 10)
    const minute = timeStr.substring(10, 12)
    const second = timeStr.substring(12, 14)
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  }
  
  // 如果是标准日期格式
  if (timeStr.includes('-') || timeStr.includes('/')) {
    return new Date(timeStr).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
  
  return timeStr
}

// 切换交易流水抽屉
const toggleTradeLogs = async (machine) => {
  if (expandedMachine.value && expandedMachine.value.id === machine.id) {
    // 如果当前机具已展开，则收起
    expandedMachine.value = null
    tradeLogs.value = []
    currentPage.value = 1
    hasMoreLogs.value = false
  } else {
    // 展开新的机具
    expandedMachine.value = machine
    tradeLogs.value = []
    currentPage.value = 1
    hasMoreLogs.value = false
    await getTradeLogs()
  }
}

// 获取交易流水
const getTradeLogs = async () => {
  if (tradeLogsLoading.value || !expandedMachine.value) return
  
  tradeLogsLoading.value = true
  
  try {
    const response = await post(ApitestUrl + '/api/LishuaCallback/getMachineTradeLogs', {
      possn: expandedMachine.value.possn,
      page: currentPage.value,
      limit: pageSize
    })

    if (response.code === 1) {
      const newLogs = response.data.data || []
      if (currentPage.value === 1) {
        tradeLogs.value = newLogs
      } else {
        tradeLogs.value.push(...newLogs)
      }
      hasMoreLogs.value = response.data.has_more
    } else {
      uni.showToast({
        title: response.msg || '获取失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取交易流水失败:', error)
    uni.showToast({
      title: '获取失败，请重试',
      icon: 'none'
    })
  } finally {
    tradeLogsLoading.value = false
  }
}

// 加载更多交易流水
const loadMoreLogs = async () => {
  if (hasMoreLogs.value && !tradeLogsLoading.value) {
    currentPage.value++
    await getTradeLogs()
  }
}

// 页面加载时获取机具列表
onMounted(() => {
  getMachines()
})
</script>

<style lang="scss" scoped>
.machine-bind-page {
  padding: 20rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 50rpx;
  padding: 30rpx 20rpx;
  background: white;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  
  .title {
    font-size: 40rpx;
    font-weight: bold;
    background: linear-gradient(135deg, #667eea, #764ba2);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
  
  .subtitle {
    display: block;
    font-size: 26rpx;
    color: #666;
    margin-top: 12rpx;
    font-weight: 400;
  }
}


.machine-list {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #f0f0f0;
  
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .list-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  
  .empty {
    text-align: center;
    padding: 80rpx 0;
    color: #999;
    font-size: 28rpx;
    background: #fafafa;
    border-radius: 12rpx;
    border: 2rpx dashed #e0e0e0;
    margin-top: 20rpx;
  }
  
  .machine-items {
    .machine-item {
      background: #fafafa;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      border: 1rpx solid #e8e8e8;
      position: relative;
      transition: all 0.3s ease;
      overflow: hidden;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      &:hover {
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        transform: translateY(-2rpx);
      }
      
      &.expanded {
        background: white;
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
        border-color: #1890ff;
        transform: translateY(-4rpx);
      }
      
      .machine-info {
        .info-row {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;
          padding: 8rpx 0;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .label {
            font-size: 26rpx;
            color: #666;
            width: 160rpx;
            font-weight: 500;
          }
          
          .value {
            font-size: 26rpx;
            color: #333;
            flex: 1;
            font-weight: 400;
            
            &.status {
              display: inline-block;
              padding: 6rpx 16rpx;
              border-radius: 20rpx;
              font-size: 22rpx;
              font-weight: 500;
              width: auto;
              max-width: fit-content;
              
              &.active {
                background: linear-gradient(135deg, #f6ffed, #e6f7ff);
                color: #52c41a;
                border: 1rpx solid #b7eb8f;
                box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.2);
              }
              
              &:not(.active) {
                background: linear-gradient(135deg, #fff2f0, #ffe7e6);
                color: #ff4d4f;
                border: 1rpx solid #ffccc7;
                box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.2);
              }
            }
          }
        }
      }
      
      .machine-actions {
        position: absolute;
        top: 20rpx;
        right: 20rpx;
        
        .machine-status {
          .status-text {
            background: linear-gradient(135deg, #52c41a, #73d13d);
            color: white;
            padding: 8rpx 18rpx;
            border-radius: 25rpx;
            font-size: 22rpx;
            font-weight: 600;
            box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.4);
            text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
            
            &.inactive {
              background: linear-gradient(135deg, #ff7875, #ff4d4f);
              box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.4);
            }
          }
        }
      }
      
      .machine-footer {
        margin-top: 20rpx;
        padding-top: 20rpx;
        border-top: 1rpx solid #f0f0f0;
        display: flex;
        justify-content: center;
        
        .view-logs-btn {
          color: #1890ff;
          font-size: 26rpx;
          font-weight: 500;
          padding: 8rpx 16rpx;
          border-radius: 8rpx;
          transition: all 0.3s ease;
          position: relative;
          cursor: pointer;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 2rpx;
            left: 50%;
            width: 0;
            height: 2rpx;
            background: linear-gradient(90deg, #1890ff, #40a9ff);
            transition: all 0.3s ease;
            transform: translateX(-50%);
          }
          
          &:hover {
            color: #40a9ff;
            background: rgba(24, 144, 255, 0.05);
            
            &::after {
              width: 80%;
            }
          }
          
          &:active {
            transform: scale(0.98);
            color: #096dd9;
          }
        }
      }
      
      // 交易流水抽屉样式
      .trade-drawer {
        margin-top: 20rpx;
        padding-top: 20rpx;
        border-top: 1rpx solid #e8e8e8;
        animation: slideDown 0.3s ease-out;
        
        .drawer-header {
          margin-bottom: 20rpx;
          padding: 16rpx 20rpx;
          background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
          border-radius: 8rpx;
          border-left: 4rpx solid #1890ff;
          
          .drawer-title {
            font-size: 28rpx;
            font-weight: bold;
            color: #1890ff;
            display: block;
            margin-bottom: 4rpx;
          }
          
          .drawer-subtitle {
            font-size: 24rpx;
            color: #666;
          }
        }
        
        .loading-logs {
          text-align: center;
          padding: 40rpx 0;
          color: #999;
          font-size: 26rpx;
        }
        
        .empty-logs {
          text-align: center;
          padding: 60rpx 0;
          color: #999;
          font-size: 26rpx;
          background: #f8f9fa;
          border-radius: 8rpx;
          border: 1rpx dashed #d9d9d9;
        }
        
        .trade-logs {
          .trade-log-item {
            background: white;
            border-radius: 8rpx;
            padding: 20rpx;
            margin-bottom: 16rpx;
            border: 1rpx solid #f0f0f0;
            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
            transition: all 0.2s ease;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            &:hover {
              box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
              transform: translateY(-1rpx);
            }
            
            .log-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 12rpx;
              
              .log-amount {
                font-size: 30rpx;
                font-weight: bold;
                color: #333;
              }
              
              .log-status {
                padding: 4rpx 12rpx;
                border-radius: 16rpx;
                font-size: 20rpx;
                font-weight: 500;
                
                &.success {
                  background: #f6ffed;
                  color: #52c41a;
                  border: 1rpx solid #b7eb8f;
                }
                
                &.failed {
                  background: #fff2f0;
                  color: #ff4d4f;
                  border: 1rpx solid #ffccc7;
                }
              }
            }
            
            .log-details {
              .detail-row {
                display: flex;
                align-items: flex-start;
                margin-bottom: 6rpx;
                
                &:last-child {
                  margin-bottom: 0;
                }
                
                .label {
                  font-size: 22rpx;
                  color: #666;
                  width: 120rpx;
                  flex-shrink: 0;
                  margin-top: 2rpx;
                }
                
                .value {
                  font-size: 22rpx;
                  color: #333;
                  flex: 1;
                  word-break: break-all;
                  line-height: 1.4;
                }
              }
            }
          }
        }
        
        .load-more-logs {
          text-align: center;
          margin-top: 20rpx;
          
          .load-more-btn {
            display: inline-block;
            padding: 12rpx 24rpx;
            background: linear-gradient(135deg, #1890ff, #40a9ff);
            color: white;
            border-radius: 20rpx;
            font-size: 24rpx;
            font-weight: 500;
            box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.3);
            transition: all 0.3s ease;
            
            &:active {
              transform: scale(0.95);
              box-shadow: 0 1rpx 4rpx rgba(24, 144, 255, 0.5);
            }
          }
        }
      }
    }
  }
}

// 抽屉展开动画
@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
    transform: translateY(-20rpx);
  }
  to {
    opacity: 1;
    max-height: 1000rpx;
    transform: translateY(0);
  }
}
</style>
